<?php

namespace Yesgooo\DynamicDatabaseManager\DataBaseManager;

use Illuminate\Container\Container as IlluminateContainer;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Events\Dispatcher;

class DynamicDataBaseManager
{
    protected $capsule;
    protected $config = [];

    private static $instance = null;

    private function __construct($config = [])
    {
    }

    private function __clone()
    {
    }

    public static function getInstance($config = [])
    {
        if (self::$instance === null) {
            self::$instance = new self($config);
            self::$instance->capsule = new Capsule(IlluminateContainer::getInstance());
            self::$instance->config = $config;
        }
        return self::$instance;
    }

    /**
     * 构建数据库连接
     * @param int $tenantId 租户id
     * @return \Illuminate\Database\Connection
     */
    public function buildConnection(int $tenantId = 0)
    {
        $method = config('plugin.yesgooo.dynamic-database-manager.conf.method') ?? 'header';
        //如外部指定租户直接取指定值，否则从请求头部获取当前租户标识，默认0
        $flag = $tenantId ?: \request()->$method(config('plugin.yesgooo.dynamic-database-manager.conf.flag'), 0);

        //当前公司数据库名称，如未传公司ID取默认配置数据库名
        $database = $flag ? config('plugin.yesgooo.dynamic-database-manager.conf.database_prefix').$flag : config('plugin.yesgooo.dynamic-database-manager.conf.default_database');

        //当前的数据库连接名称
        $curConnect = $flag ? config('plugin.yesgooo.dynamic-database-manager.conf.conn_prefix') . $flag : 'default';

        $config = $this->config ?: [
            'driver' => 'mysql',
            'host'        => config('plugin.yesgooo.dynamic-database-manager.conf.host'),
            'port'        => config('plugin.yesgooo.dynamic-database-manager.conf.port'),
            'database'    => $database,
            'username'    => config('plugin.yesgooo.dynamic-database-manager.conf.username'),
            'password'    => config('plugin.yesgooo.dynamic-database-manager.conf.password'),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
        ];

        $defaultConnect = $this->capsule->getDatabaseManager()->getDefaultConnection();

        //通过容器获取全部数据库连接
        $allConnect = $this->capsule->getContainer()['config']['database.connections'];

        //如果当前连接还没有，则新增连接
        if(!in_array($curConnect, array_keys($allConnect))){
            $this->capsule->addConnection($config, $curConnect); // TODO: Change the autogenerated stub
        }

        //如果默认连接不是当前连接，则设置成默认连接
        if($defaultConnect != $curConnect){
            //断开当前连接 2023-12-13
            $this->capsule->getDatabaseManager()->disconnect();
            //重置默认连接
            $this->capsule->getDatabaseManager()->setDefaultConnection($curConnect);
        }

        $this->capsule->setAsGlobal();

        $this->capsule->bootEloquent();
    }

}